package com.tio.showcase.packet;

import com.tio.showcase.common.ShowcasePacket;
import com.tio.showcase.common.ShowcaseSessionContext;
import com.tio.showcase.common.Type;
import com.tio.showcase.showcaseintf.AbsShowcaseBsHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.tio.core.Aio;
import org.tio.core.ChannelContext;
import org.tio.utils.json.Json;

import java.util.concurrent.atomic.AtomicLong;

/**
 * Author      : liyuemin
 * Time        : 2017/12/15 15:15
 * Description :
 */
public class LoginReqHandler extends AbsShowcaseBsHandler<LoginReqbody> {
    private static Logger log = LoggerFactory.getLogger(LoginReqHandler.class);

    AtomicLong tokenseq = new AtomicLong();
    @Override
    public Class<LoginReqbody> bodyClass() {
        return LoginReqbody.class;
    }

    @Override
    public Object handle(ShowcasePacket showcasePacket, LoginReqbody bsBody, ChannelContext channelContext) throws Exception {
        log.info("收到登录请求消息:{}", Json.toJson(bsBody));
        //设置返回消息
        LoginResbody loginResbody = new LoginResbody();
        loginResbody.setCode(LoginResbody.Code.SUCCESS);
        loginResbody.setToken(newToken());

        String userid = bsBody.getLoginname();
        //记录此次id
        Aio.bindUser(channelContext,userid);


        ShowcaseSessionContext showcaseSessionContext = (ShowcaseSessionContext) channelContext.getAttribute();
        showcaseSessionContext.setUserid(userid);

        ShowcasePacket respPacket = new ShowcasePacket();
        respPacket.setType(Type.LOGIN_RESP);
        respPacket.setBody(Json.toJson(loginResbody).getBytes(ShowcasePacket.CHARST));
        Aio.send(channelContext,respPacket);
        return null;
    }
    private String newToken(){
        return System.currentTimeMillis()+"_"+tokenseq.incrementAndGet();
    }
}
